import enquireJs from "enquire.js";
import Cookie from "js-cookie";
import { request } from "@/utils/request";
import CryptoJS from 'crypto-js';

export function isDef(v) {
  return v !== undefined && v !== null;
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item);
    if (index > -1) {
      return arr.splice(index, 1);
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === "[object RegExp]";
}

//获取base64图片
export function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

//文件大小显示
export function fileSize(size) {
  if (!size) return "";
  return size < 1024
    ? size + " B"
    : size < Math.pow(1024, 2)
    ? (size / 1024).toFixed(2) + " KB"
    : size < Math.pow(1024, 3)
    ? (size / Math.pow(1024, 2)).toFixed(2) + " MB"
    : size < Math.pow(1024, 4)
    ? (size / Math.pow(1024, 3)).toFixed(2) + " GB"
    : (size / Math.pow(1024, 4)).toFixed(2) + " TB";
}

//平级数据转成树形
export function ArrayToTree(data) {
  let result = data.reduce(function(prev, item) {
    prev[item.p_id] ? prev[item.p_id].push(item) : (prev[item.p_id] = [item]);
    return prev;
  }, {});
  for (let prop in result) {
    result[prop].forEach(function(item) {
      result[item.key] ? (item.children = result[item.key]) : "";
    });
  }
  result = result[0];
  return result;
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true);
    },
    unmatch: function() {
      call && call(false);
    }
  };
  enquireJs.register("only screen and (max-width: 767.99px)", handler);
}

//添加header
export function handleImg(url, id) {
  let config = {
    responseType: "blob",
    headers: {
      Authorization: Cookie.get("Authorization")
    }
  };
  return request(url, "get", {}, config).then(response => {
    // 处理返回的文件流
    console.log(response);
    const blob = response.data;
    const img = document.getElementById(id);
    img.src = window.URL.createObjectURL(blob);
    console.log(img.src);
    window.setTimeout(function() {
      window.URL.revokeObjectURL(blob);
    }, 0);
  });
}
//json流转json
export function blobToJson(data){
  const file = new FileReader();//读取文件
  file.readAsText(data, 'utf-8');
  return new Promise((resolve) => {
    file.onload = () => {
      const message = JSON.parse(file.result);
      resolve(message);
    }
  })
}
//文件导出
export function exportExcel(obj, title, type = 'excel'){
  const link = document.createElement('a');
  let blob;
  if(type == 'excel'){
    blob = new Blob([obj], {type: 'application/vnd.ms-excel'});
  } else if(type == 'doc') {
    blob = new Blob([obj], {type: 'application/msword'});
  } else if(type == 'pdf') {
    blob = new Blob([obj], {type: 'application/pdf'});
  }
  link.style.display = 'none';
  link.href = URL.createObjectURL(blob);
  link.setAttribute('download', title);
  document.body.appendChild(link);
  link.click();
  window.setTimeout(function() {
    URL.revokeObjectURL(blob)
    document.body.removeChild(link)
  }, 0)
}
const _toString = Object.prototype.toString;

//判断是否是空对象
export function isEmptyObj(obj) {
  return JSON.stringify(obj) == "{}" ? true : false;
}

export function arrDistinct(arr) {
  const newArr = new Set(arr);
  return [...newArr];
}
export function arrDistinctByProp(arr, prop) {
  let obj = {};
  return arr.reduce(function(preValue, item) {
    obj[item[prop]] ? "" : (obj[item[prop]] = true && preValue.push(item));
    return preValue;
  }, []);
}
export function sortKey(array, key) {
  return array.sort(function(a, b) {
    var x = a[key];
    var y = b[key];
    return x > y ? -1 : x < y ? 1 : 0;
  });
}
//加密
export function encrypt(word, keyStr) {
  keyStr = keyStr ? keyStr : 'rsnsrsnsrsnsrsns';
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.toString();
}

//重置对象
export function clearObj(obj){
    for(let key in obj){
        obj[key]  = ''
    }
}
export function getPlainText(richCont){
  let value = richCont;
  if(richCont){
    value= value.replace(/\s*/g, "");  //去掉空格
    value= value.replace(/<[^>]+>/g, ""); //去掉所有的html标记
    value = value.replace(/↵/g, "");     //去掉所有的↵符号
    value = value.replace(/[\r\n]/g, "") //去掉回车换行
    value = value.replace(/&nbsp;/g, "") //去掉空格
    value = convertIdeogramToNormalCharacter(value);
    return value;
  } else {
    return '';
  }
}
function convertIdeogramToNormalCharacter(val) {
  const arrEntities = {'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"','ldquo':'“','rdquo':'”','lsquo':'‘','rsquo':'’'};
  return val.replace(/&(lt|gt|nbsp|amp|quot|ldquo|rdquo|lsquo|rsquo);/ig,function(all,t){return arrEntities[t];});
}
function normalCharacterToConvertIdeogram(val) {
  const arrEntities = {'<':'lt','>':'gt',' ':'nbsp','&':'amp','"':'quot','“':'ldquo','”':'rdquo','‘':'lsquo','’':'rsquo'};
  return val.replace(/(<|>| |&|"|“|”|‘|’)/ig,function(all,t){return '&' + arrEntities[t] + ';';});
}
export function getPlayTime(time){
	let hours = Math.floor(time / 3600);
	let minute = Math.floor(Math.floor(time % 3600) / 60);
	let second = time % 60;
	hours = hours.toString().length === 1 ? `0${hours}` : hours;
	minute = minute.toString().length === 1 ? `0${minute}` : minute;
	second = second.toString().length === 1 ? `0${second}` : second;
	return hours + ":" + minute + ":" + second;
}
export const labelColorMap = {
  错别字: '#46B1FF',
  意识形态: '#E05F5F',
  严重敏感信息: '#EBC643',
  诗词审核: '#17805A',
  法律法规: '#36CDCD',
  个人信息: '#FA906C',
  科技名词: '#7A53E5',
  自定义词: '#78B45C',
  其它敏感信息: '#FA8701'
}
//按索引高亮
export function createHighlight(str, errIndex, label){
  return '<span class="highlight" id="errIndex'+ errIndex +'"' + ' style="border-bottom: 3px solid '+labelColorMap[label]+';">' + str + '</span>';
}
export function underlineWord(dom, label){
  dom.style.borderBottom = `3px solid ${labelColorMap[label]}`;
}
export function markWord(dom, color){
  dom.style.backgroundColor = color;
}
//查找错敏词
export function seekWord(item, convertRichText = false){
  //查出带问号的错词会与正则表达式产生冲突
  item = item.replace('?','\\?');
  item = item.replace('.','\\.');
  //把特殊符号转为富文本的形式
  if(convertRichText){
    item = normalCharacterToConvertIdeogram(item);
  }
  //找前后不被高亮span标签包裹的词
  let reg = new RegExp('(?!;">)'+item+'(?!</span>)');
  return reg;
}
//在字符串中插入字符串
export function insertStr(str, index, insertStr){
  let arr = str.split('');
  arr.splice(index, 0, insertStr);
  return arr.join('');
}
//获取url参数
export function getQueryParams(url) {
  const paramArr = url.slice(url.indexOf("?") + 1).split("&");
  const params = {};
  paramArr.map((param) => {
      const [key, val] = param.split("=");
      params[key] = decodeURIComponent(val);
  });
  return params;
}

export function cutStat(number) {
  let unit = '';
  if(number > 100000000){
    number = parseFloat((number / 100000000).toFixed(1));
    unit = '亿';
  }
  // else if(number > 10000000){
  //   number = parseFloat((number / 10000000).toFixed(1));
  //   unit = '千万';
  // }
  // else if(number > 1000000){
  //   number = parseFloat((number / 1000000).toFixed(1));
  //   unit = '百万';
  // }
  else if(number >= 10000){
    number = parseFloat((number / 10000).toFixed(1));
    unit = '万'
  }

  return {
    number,
    unit
  };
}


//获取检测耗时
export function getCheckElapsedTime(startTime, endTime) {
  let elapsedTime = new Date(endTime) - new Date(startTime);
  console.log(elapsedTime);
  if (elapsedTime > 0) {
    if (elapsedTime < 1000){
      elapsedTime = "小于1秒"
    } else if (elapsedTime < 60000){
      elapsedTime = (elapsedTime / 1000).toFixed(0) + '秒';
    } else if (elapsedTime < 3600000){
      elapsedTime = (elapsedTime / 60000).toFixed(0) + '分' + ((elapsedTime % 60000) / 1000).toFixed(0) + '秒';
    }
    else{
      elapsedTime = (elapsedTime / 3600000).toFixed(1) + '小时';
    }
  }else if (elapsedTime === 0){
    elapsedTime = "小于1秒"
  }else {
    elapsedTime = "";
  }
  return elapsedTime;
}

//根据文件类型获取上传组件支持的格式
export function getAUploadAccept(taskType) {
  let accept = "";
  if (taskType === 'bigFile') {
    accept = 'application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation';
  } else if (taskType === 'video') {
    accept = '';
  } else if (taskType === 'audio') {
    accept = 'audio/ogg,audio/mpeg';
  } else if (taskType === 'image') {
    accept = 'image/bmp, image/jpg, image/jpeg, image/png, image/gif, image/webp, image/tiff';
  }
  return accept;
}

//生成任务名称
export function generateTaskName(fileName, taskType) {
  let name = '未命名文件';
  if (taskType === 'bigFile') {
    name = '未命名图文文件';
  } else if (taskType === 'video') {
    name = '未命名视频文件';
  } else if (taskType === 'audio') {
    name = '未命名音频文件';
  } else if (taskType === 'image') {
    name = '未命名图片文件';
  }
  let date = new Date();
  let year = date.getFullYear(); // 年
  let month = date.getMonth() + 1; // 月
  let day = date.getDate(); // 日
  let hour = date.getHours(); // 时
  let minutes = date.getMinutes(); // 分
  let d1 = year + '' + month + '' + day + '-';
  let d2 = hour + '' + minutes;
  let taskName = name + d1 + '' + d2 + '.' + getFileSffix(fileName);
  return taskName;
}

//生成任务名称
export function getFileSffix (filename) {
  let parts = filename.split(".");
  let sffix = parts[parts.length - 1];
  return sffix;
}
